package com.yeci.controller;

import com.yeci.utils.SaSecureUtil;
import com.yeci.common.AjaxResult;
import com.yeci.common.controller.BaseController;
import com.yeci.common.page.TableDataInfo;
import com.yeci.entity.SysUser;
import com.yeci.mapper.SysUserMapper;
import com.yeci.service.SysUserService;
import com.yeci.utils.SaltUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yeci
 * @since 2021-08-01
 */
@Slf4j
@RestController
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {
  @Autowired
  private SysUserMapper userMapper;

  @Autowired
  private SysUserService userService;

  /**
   * 查询用户列表
   * @param sysUser 用户对象
   * @return
   */
  @GetMapping("/list")
  public TableDataInfo list(SysUser sysUser) {
    List<SysUser> sysUsers = userService.selectUserList(sysUser);
    return getDataTable(sysUsers);
  }

  /**
   * 根据用户名查询
   * @param username
   * @return
   */
  @GetMapping("/byUserName/{username}")
  public AjaxResult getByUserName(@PathVariable("username") String username){
    return AjaxResult.success(userMapper.selectByUserName(username));
  }

  /**
   * 根据Id查询用户
   * @param id
   * @return
   */
  @GetMapping("/user/{id}")
  public AjaxResult getUser(@PathVariable("id") String id){
    return AjaxResult.success(userMapper.selectById(id));
  }

  /**
   * 修改用户
   * @param sysUser
   */
  @PostMapping("/updateUser")
  public AjaxResult updateUser(@RequestBody SysUser sysUser){
     return AjaxResult.toAjax(userMapper.updateById(sysUser));
  }

  /**
   * 新增用户
   * @param sysUser
   */
  @PostMapping("/addUser")
  public AjaxResult addUser(@RequestBody SysUser sysUser){
    String salt = SaltUtil.getSalt(20);
    sysUser.setSalt(salt);
    sysUser.setPassword(SaSecureUtil.md5BySalt(sysUser.getPassword(),salt));
    return AjaxResult.toAjax(userMapper.insert(sysUser));
  }

  /**
   * 删除用户
   * @param id
   * @return
   */
  @GetMapping("/deleteUser/{id}")
  public AjaxResult deleteUser(@PathVariable("id") String id){
    return AjaxResult.toAjax(userMapper.deleteById(id));
  }

  /**
   * 查询用户名是否存在
   * @param username
   * @return
   */
  @GetMapping("/checkUsername/{username}")
  public AjaxResult checkUsername(@PathVariable String username) {
    int i = userMapper.checkUserName(username);
    if(i > 0){
      return AjaxResult.error("用户名已存在！！");
    }
    return AjaxResult.success("用户名可用！！");
  }
}

